<template>
  <el-col :span="opt.reportType==='line'?24:12">
    <div class="bg-purple-dark" :style="{height:'540px'}">
      <div class="cardInformation">
        <div class="blueIcon" />
        <div class="dataName">{{ chartCardName }}</div>
        <div v-if="closeSeven" class="recentlyDay">{{ $t('manage.nearSeven') }}</div>
        <div v-if="linkage" class="recentlyDay">{{ $t('manage.linkage') }}</div>
        <div v-if="opt.reportType==='line'" class="tabChartName">
          <el-button type="primary" size="mini" :plain="conditions.type==='month' || conditions.type==='quarter'" round @click="onRanking('day')">{{ $t('manage.nearThirty') }}</el-button>
          <el-button type="primary" size="mini" :plain="conditions.type==='month' || conditions.type==='day'" round @click="onRanking('quarter')">{{ $t('manage.nearNuarter') }}</el-button>
          <el-button type="primary" size="mini" :plain="conditions.type==='day' || conditions.type==='quarter'" round @click="onRanking('month')">{{ $t('manage.nearYear') }}</el-button>
        </div>
        <div v-if="changeChart" class="tabChartName">
          <el-button type="primary" size="mini" :plain="warehouseBtn==='qty'" round @click="onAgeAnalysis('amount')">{{ $t('manage.StockAmount') }}</el-button>
          <el-button type="primary" size="mini" :plain="warehouseBtn==='amount'" round @click="onAgeAnalysis('qty')">{{ $t('manage.productsNum') }}</el-button>
        </div>
      </div>
      
      <div v-if="chartData.rows&&!!chartData.rows.length" class="dataBox">
        <ve-chart :data="chartData" :settings="chartSettings" :extend="chartExtend" :events="tenDepChartEvents" />
      </div>
      <NoData v-if="chartData.rows &&!chartData.rows.length" />
    </div>
  </el-col>
</template>

<script>
import NoData from '@/components/NoData'

export default {
  name: 'ChartCard',
  components: {
    NoData
  },
  props: {
    chartCardName: {
      type: String,
      default: ''
    },
    chartData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    opt: {
      type: Object,
      default: () => {
        return {}
      }
    },
    closeSeven: { // 近7天排行
      type: Boolean,
      default: false,
    },
    isStock: { 
      type: Boolean,
      default: false,
    },
    linkage: { 
      type: Boolean,
      default: false,
    },
    changeChart: { // 切换图
      type: Boolean,
      default: false,
    }
  },
  data() {
    const self = this
    this.tenDepChartEvents = {
      click: (e) => {
        self.tenDepChartClicked(e)
      }
    }
    return {
      conditions: {type: 'day'},
      selectedDepIndex: 0, // 鼠标点击选中的数据项，默认是第一个（0项）
      warehouseBtn: 'amount'
    }
  },
  computed: {
    chartSettings() { // 私有属性
      const { columns = [] } = this.chartData
      const { reportType = 'histogram' } = this.opt
      
      const sellLengedName = [this.$t('manage.xName'), this.$t('manage.sale'), this.$t('manage.returns')]
      const stockLengedName = [this.$t('manage.xName'), this.$t('manage.stock'), this.$t('manage.returns')]

      const labelMap =
        columns &&
        columns.reduce((newData, value, index) => {
          const newKey = columns[index]
          newData[newKey] = this.isStock ? stockLengedName[index] : sellLengedName[index]
          return newData
        }, {})
      
      let chartSettings
      switch (reportType) {
        case 'histogram':
          if (columns.length > 2) {
            chartSettings = {
              type: 'histogram',
              // showLine: columns[2],
              // axisSite: {right: ['saleReturnRatio'] }, // 双y轴设置
              yAxisType: ['KMB', 'percent'], // 双y轴类型
              yAxisName: [this.$t('manage.returnsNum'), this.$t('manage.returns')],
              labelMap: {
                'returnNumbers': this.$t('manage.returnsNum'),
                'saleReturnRatio': this.$t('manage.returns'),
              },
            }
          } else {
            chartSettings = {
              type: 'histogram',
              labelMap: {
                'value': this.$t('manage.goodsNum'),
              },
            }
          }
          break
        case 'line':
          chartSettings = {
            type: 'line',
            labelMap
          }
          break
        case 'pie':
          chartSettings = {
            type: 'pie'
          }
          break
        case 'ring':
          chartSettings = {
            type: 'ring'
          }
          break
        default:
          return null
      }
      return {...chartSettings}
    },
    chartExtend() {
      const { reportType = 'histogram' } = this.opt
      const newIndex = this.selectedDepIndex // 需要存一下才获取到

      var that = this
      const chartExtend = {
        xAxis: this.getxAxis(reportType),
        yAxis: this.getyAxis(reportType),
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let html = params[0].name + '<br>'
            for (let i = 0; i < params.length; i++) {
              html += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + params[i].color + ';"></span>'
              if (params[i].seriesType === 'line' && params[i].componentIndex === 0) {
                html += params[i].seriesName + ':' + params[i].value[1] + '<br>'
              } else if (params[i].componentIndex > 0) {
                html += params[i].seriesName + ':' + ((params[i].value) * 100).toFixed(2) + '%<br>'
              } else {
                html += params[i].seriesName + ':' + params[i].value + '<br>'
              }
            }
            return html
          }
        },
        series(v) {
          const dt = v[0].data
          for (let i = 0; i < dt.length; i++) {
            if (dt[i].value === 0) {
              dt[i].label = {show: false}
              dt[i].labelLine = {show: false}
            }
          }
          const newNames = []
          const newDatas = []
          if (v.length > 1) {
            newNames.push(v[0].name, v[1].name)
            newDatas.push(v[0].data, v[1].data)
          }
          const chartSer = [{
            type: reportType === 'histogram' ? 'bar' : reportType === 'ring' ? 'pie' : reportType,
            data: v[0].data,
            name: v[0].name,
            center: window.screen.width < 1280 ? ['30%', '60%'] : ['40%', '60%'], // 位置
            radius: window.screen.width < 1280 ? '50%' : '60%',
            label: that.label(reportType),
            symbolSize: 9,
            smooth: false, // 折线
            lineStyle: {
              width: 3.5
            },
            barWidth: 50,
            
            itemStyle: reportType === 'histogram' && v.length < 2 && {
              normal: {
              // 这里是重点
                color: (params) => {
                  // 注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                  const colorList = ['#1974C8', '#5496F2', '#BADDFF', '#FCB67C', '#F37964']
                  return newIndex === params.dataIndex ? colorList[params.dataIndex] : that.hexToRgba(colorList[params.dataIndex], 0.3)
                }
              }
            }
          }, v.length > 1 ? {
            type: 'line',
            data: v[1].data,
            name: v[1].name,
            symbolSize: 9,
            smooth: false, // 折线
            lineStyle: {
              width: 3.5
            },
            yAxisIndex: 1, // 显示双y
            valueType: 'percent',
          } : '']
          return chartSer
        },
        color: ['#5496F2', '#F3647C', '#13C2C2', '#2FC25B', '#FACC14', '#c39d86'],
        legend: that.getLegend(reportType),
        grid: {
          x: 30,
          x2: 20,
          y2: 1, // 距离下端位置
        },
      }
      return chartExtend
    }
  },
  watch: {
    conditions: {
      handler(newName, oldName) {
        this.conditions = newName
      },
      immediate: true
    }
  },
  methods: {
    getxAxis(type) {
      const {columns = []} = this.chartData
      let res
      switch (type) {
        case 'pie':
          return null
        case 'histogram':
          if (columns.length > 2) {
            res = {
              isLine: {
                show: true,
                lineStyle: {
                  width: 2,
                  color: '#6B6B6B'
                },
              },
              axisLabel: {  
                interval: 0,  
                rotate: 40, // 旋转
                formatter: function(value) { // 超出部分省略
                  return (value.length > 4 ? (value.slice(0, 3) + '...') : value)
                },
              },
              axisTick: {
                show: true,
                alignWithLabel: true
              },
            }
          } else {
            res = {
              axisLine: {
                show: true,
                lineStyle: {
                  width: 2,
                  color: '#6B6B6B'
                }
              },
              axisTick: {
                show: true,
                alignWithLabel: true
              },
            }
          }
          break
        case 'line':
          res = {
            axisLine: {
              show: true,
              lineStyle: {
                width: 1,
                color: '#6B6B6B'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
              inside: true
            }
          }
          break
        case 'ring':
          return null
        default:
          return null
      }
      return {
        ...res
      }
    },
    getyAxis(type) {
      const {columns = []} = this.chartData

      const sellLengedName = [this.$t('manage.xName'), this.$t('manage.sale'), this.$t('manage.returns')]
      const stockLengedName = [this.$t('manage.xName'), this.$t('manage.stock'), this.$t('manage.returns')]
      
      const labelMap =
        columns &&
        columns.reduce((newData, value, index) => {
          const newKey = columns[index]
          newData[newKey] = this.isStock ? stockLengedName[index] : sellLengedName[index]
          return newData
        }, {})
      let res
      switch (type) {
        case 'pie':
          return null
        case 'ring':
          return null
        case 'histogram':
          if (columns.length > 2) {
            res = {
              // position: 'right',
              axisLine: {
                show: false,
              },
              splitLine: {
                lineStyle: {
                  type: 'dotted', // 虚线
                }
              }
            }
          } else {
            res = {
              position: 'left',
              axisLabel: {
                show: false
              },
              splitLine: {
                show: false,
              }
            }
          }
          break
        case 'line':
          res = {
            name: labelMap.amount || labelMap.buyAmount,
            nameLocation: 'end',
            position: 'left',
            axisLine: {
              show: true,
              color: '#6B6B6B'
            },
            splitLine: {
              lineStyle: {
                type: 'dotted', // 虚线
              }
            }
          }
          break
        default:
          return null
      }
      return {
        ...res
      }
    },
    getLegend(type) {
      const {columns = []} = this.chartData
      let res
      switch (type) {
        case 'pie':
          res = {
            orient: 'vertical',
            top: '36%',
            right: window.screen.width < 1440 ? '0' : '5%',
            itemGap: 30, // 间隔
            icon: 'circle', // 圆点
            textStyle: {
              color: '#000',
              fontSize: 15
            }
          }
          break
        case 'ring':
          res = {
            orient: 'vertical',
            top: '36%',
            right: window.screen.width < 1440 ? '0' : '5%',
            itemGap: 30, // 间隔
            icon: 'circle', // 圆点
            textStyle: {
              color: '#000',
              fontSize: 15
            }
          }
          break
        case 'histogram':
          if (columns.length > 2) {
            res = {
              orient: 'horizontal', // 垂直
              right: '1%',
              itemGap: 15, // 间隔
              textStyle: {
                color: '#000',
                fontSize: 15
              },
            }
          } else {
            res = {
              orient: 'horizontal', // 垂直
              right: '1%',
              itemGap: 15, // 间隔
              textStyle: {
                color: '#000',
                fontSize: 15
              },
              icon: 'image:///img/legend.png',
              itemWidth: 80, // 改变图例图片宽
            }
          }
          break
        case 'line':
          res = {
            selectedMode: false, // 点击事件
            orient: 'horizontal', // 垂直
            right: '1%',
            itemGap: 15, // 间隔
            textStyle: {
              color: '#000',
              fontSize: 15
            }
          }
          break
        default:
          return null
      }
      return {
        ...res
      }
    },
    label(type) {
      const {columns = []} = this.chartData

      let res
      switch (type) {
        case 'pie':
          res = {
            formatter: '{b}:({d}%)'
          }
          break
        case 'histogram':
          if (columns.length > 2) { // 混合图不显示
            res = {
              show: false, 
            }
          } else {
            res = {
              show: true, // histogram
              color: '#000',
              position: 'outside',
              borderColor: '#DFDFDF',
              borderWidth: 1,
              lineHeight: 10,
              borderRadius: [2, 2, 2, 2],
              padding: [6, 6, 6, 6]
            }
          }
          break
        case 'line':
          res = {
            show: false, 
          }
          break
        default:
          return null
      }
      return {
        ...res
      }
    },
    onRanking(type) {
      this.conditions = {type}
      this.$emit('sendType', type)
    },
    tenDepChartClicked(e) {
      const value = e && e.name
      const newValue = value.split(/[\'天'\'day']/)
      this.$emit('sendData', newValue[0])
      this.reFreshDepTen()
    },
    // 刷新图表：清空图表数据再重新赋值，只有图表数据变化了图表才会重新绘制
    reFreshDepTen() {
      const temp = this.chartData.rows
      this.chartData.rows = []
      this.chartData.rows = temp
    },
    hexToRgba(hex, opacity) { // 颜色透明方法
      return hex && hex.replace(/\s+/g, '').length === 7 ? 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' +
          parseInt('0x' + hex.slice(3, 5)) + ',' +
          parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')' : ''
    },
    onAgeAnalysis(e) { // 切换图表按钮
      this.warehouseBtn = e
      this.$emit('onChangeTeb', e)
    }
  }
}
</script>

<style scoped lang="scss">
    @import './style'
</style>
